<template>
	<view class="wrap">
		<js-error mode="bottom" ref="jsError"></js-error>
		<!-- <view class="action bg-white "
			style="padding: 15px 0 0 10px;font-size: 20px;align-items: center;display: flex;">
			<u-icon name="/static/image/invcode.png" size="80"></u-icon>
			<text class="cuIcon-titles text-bold">废旧物资信息</text>
		</view> -->

		<u-form class="form bg-white" :model="model" ref="uForm" label-position="left">
			<u-form-item label="材料编码:" prop="invCode" label-width="220" >
				<u-input placeholder=" " v-model="model.invCode" type="text" :disabled="true" di maxlength="64"></u-input>
			</u-form-item>
			<u-form-item label="材料名称:" prop="invName" label-width="220" >
				<u-input placeholder=" " v-model="model.invName" type="text" :disabled="true" di maxlength="64"></u-input>
			</u-form-item>
			<u-form-item label="规格型号:" prop="invStd" label-width="220">
				<u-input placeholder=" " v-model="model.invStd" type="text" :disabled="true" di maxlength="64"></u-input>
			</u-form-item>
			<view v-if="icon === 'code'">
				<u-form-item label="材料编码(新):" prop="invCode2" label-width="220" required
					:label-style="{'font-weight':'bold'}">
					<!-- <js-select v-model="model.carVenCode" :showFilter="true" :items="carVenSelectList" placeholder="请选择" :tree="true"
						:label-value="model.carVenName" @label-input="model.carVenName = $event"></js-select> -->
						<!-- <u-input placeholder="请选择" v-model="model.invCode2" type="select" @click="xzch"></u-input> -->
						<!-- <u-input placeholder="请输入" v-model="model.invCode2" type="text"  @blur="checkCode" @clear="clearCode"
							></u-input> -->
						<u-search v-model="model.invCode2" ref="uSearch" :focus="focus" placeholder="请先聚焦后扫描" :show-action="false" @search="confirm" bgColor="#fff" @clear="clearCode"></u-search>
						<text class="cuIcon-scan text-xxl" @click="search" ></text>
				</u-form-item>
						
				<u-form-item label="材料名称(新):" prop="invName2" label-width="220" >
					<u-input placeholder=" " v-model="model.invName2" :disabled="true" type="text" di maxlength="64"></u-input>
				</u-form-item>
				<u-form-item label="规格型号(新):" prop="invStd2" label-width="220" >
					<u-input placeholder=" " v-model="model.invStd2" :disabled="true" type="text" di maxlength="64"></u-input>
				</u-form-item>
				
			</view>
			<view v-else-if="icon === 'num'">
				
				<u-form-item  label="数量:" prop="iqty" label-width="220" >
					<u-input placeholder=" " v-model="model.iqty" type="text" :disabled="true" di maxlength="64"></u-input>
				</u-form-item>
				<u-form-item  label="件数:" prop="inum" label-width="220" v-if="model.bfixExch != '0'">
					<u-input placeholder=" " v-model="model.inum" type="text" :disabled="true" di maxlength="64"></u-input>
				</u-form-item>
				<u-form-item  label="剩余数量:" prop="iqty" label-width="220" :label-style="{'font-weight':'bold'}">
					<u-input placeholder=" " v-model="model.syOutQty" type="text" :disabled="true" di maxlength="64"></u-input>
				</u-form-item>
				<u-form-item  label="件数(新):" prop="inum2" label-width="220" required :label-style="{'font-weight':'bold'}" v-if="model.bfixExch != '0'" >
					<u-input placeholder=" " v-model="model.inum2" @blur="inumChange($event)" type="digit" di maxlength="200"></u-input>
				</u-form-item>
				<u-form-item label="数量(新):" prop="iqty2" label-width="220" required :label-style="{'font-weight':'bold'}">
						<u-input placeholder=" " v-model="model.iqty2" @blur="iqtyChange($event)" type="digit" di maxlength="200"></u-input>
				</u-form-item>
				
				
			</view>	
			<view v-else-if="icon ==='deptname'">
				<u-form-item label="部门:" prop="extDefine3" label-width="220" :label-style="{'font-weight':'bold'}">
					<u-input placeholder=" " v-model="model.extDefine3" type="text" :disabled="true"></u-input>

				</u-form-item>	
				<u-form-item label="部门(新):" prop="extDefine31" label-width="220" :label-style="{'font-weight':'bold'}">
					<!-- <u-input placeholder="请选择" v-model="model.depCode" type="select"  @click="xzch"></u-input> -->
					
					<js-select v-model="model.extDefine31" :showFilter="true" :items="OfficeList" placeholder="请选择" :tree="true"
						:label-value="model.extDefine31" @label-input="model.extDefine31 = $event"></js-select>
				</u-form-item>	
			</view>
		</u-form>
		
	<view style="height: 70px;"></view>
	<view class=" flex cu-bar cu-bar1 tabbar bg-white foot cu-modal-footer">
		<button class="cu-btn  lines-red lg" @click="cancel">关闭</button>
		<button class="cu-btn  bg-confirm lg  margin-left" @click="submit">保存</button>
	</view>
	</view>
</template>

<script>
	import config from '@/common/config.js'
	import util from '@/common/fire.js'
	export default {
		data() {
			return {
				params: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: true
				},
				model: {
				},
				//主表id
				query: {
					id: '',
				},
				//子表id
				querys: {
					id: '',
				},
				children: [],
				carVenSelectList: [],
				pickerTime: false, //控制日期显示
				icon: '',
				OfficeList:[],
				focus:false,
				barCode:'',
			}
		},
		onLoad(params) {
			console.log(params)
			this.model = JSON.parse(params.items)
			this.icon = params.icon
			this.getOfficeListData()
			// this.model.bfixExch = 1
			// console.log(this.model.ichangeRate,'ichangeRate')
			uni.$on('chObj', (data) => {
				this.model.invCode2 = data.invCode
				this.model.invName2 = data.invName
				this.model.invStd2 = data.invStd
				this.$forceUpdate()
			})
		},
		onShow() {},
		onReady() {
			// 运输单位数据
			// this.$u.api.mf.posTreeData().then(res => {
			// 	this.carVenSelectList = res;
			// });
		},
		methods: {
			clearCode(){
				this.model.invName2 = ''
				this.model.invStd2 = ''
				this.$forceUpdate()
			},
			checkCode(){
				if(this.model.invCode2){
					this.$u.api.mf.invForm({
						invCode:this.model.invCode2
					}).then((res)=>{
						console.log(res,'res.list.length')
							
							if(res.basInv.invCode&&res.basInv.invName){
								this.model.invName2 = res.basInv.invName
								this.model.invStd2 = res.basInv.invStd
								this.$forceUpdate()
							}else{
								this.model.invName2 = ''
								this.model.invStd2 = ''
								this.$refs.jsError.showError('', '请输入正确的存货编码或者扫描', 'error');
							}
					})
				}			
			},
			makeSound(name){
				console.log("=====testClick=====");
				let src = '/static/'+name+'.mp3';
				//实例化声音  
				const Audio = uni.createInnerAudioContext();
				Audio.autoplay = true;
				Audio.src = src; //音频地址  
				Audio.play(); //执行播放  
				Audio.onError((res) => {
				});
				Audio.onPause(function() {
					console.log('end');
					Audio.destroy();
				});
			},
			confirm() {
				this.focus = false
				this.commonSearch(this.model.invCode2)
			},
			search() {
				var _that = this;
				_that.focus = false
				if(this.vuex_config.deviceType === this.vuex_config.deviceTypeAPP){
					const wechat = uni.getSystemInfoSync()?.host?.env
					if (wechat === 'WeChat') {
					    uni.scanCode({
					    	scanType: ["barCode", "qrCode"],
					    	// onlyFromCamera: true,
					    	success: async (res) => {
					    		_that.barCode = res.result;
					    		await _that.commonSearch(res.result)
					    	},
					    });
					} else {
						var mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module");
						console.log('mpaasScanModule',mpaasScanModule)
						
						mpaasScanModule.mpaasScan({
							// 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
							'scanType':  ['qrCode','barCode'],
							// 是否隐藏相册，默认false不隐藏
							'hideAlbum': false,
							//ios需要设置这个参数，只支持中英文 zh-Hans、en，默认中文                       
							'language' : 'en',
							//相册选择照片识别错误提示(ios)
							'failedMsg': '未识别到二维码，请重试',
							//Android支持全屏需要设置此参数
							'screenType': 'full'              
						},
						async (ret) => {
							console.log('ret',ret)
							if(ret.resp_message == 'success'){
								_that.barCode = ret.resp_result;
								await _that.commonSearch(ret.resp_result)
							}
						})
					}
				}else if(this.vuex_config.deviceType === this.vuex_config.deviceTypePDA){
					_that.focus = false
					setTimeout(()=>{
						_that.focus = true
					},500)
				}
				
			},
			async commonSearch(barCode) {
				let that = this
			
				//扫存货
				if (util.checkBarcode(barCode, this.vuex_config.InventoryPrefix)) {
					this.$u.api.mf.getBarInfo({
						barCode,
					}).then(res => {
						if(res.result == 'true'){
							if (!res.error) {
								console.log(res.data,'res.data')
								this.model.invCode2 = res.data.basInv.invCode
								this.model.invName2 = res.data.basInv.invName
								this.model.invStd2 = res.data.basInv.invStd
								this.$forceUpdate()
								setTimeout(()=>{
									this.makeSound("cg");
								},500)
								that.$u.toast('验证成功！');
								// if(res.data.basInv && res.data.basInv.invCode == that.model.invCode){
								// 	that.invFlag = true
								// 	setTimeout(()=>{
								// 		that.makeSound("cg");
								// 	},500)
								// 	that.$u.toast('验证成功！');
								// }else{
								// 	setTimeout(()=>{
								// 		that.makeSound("sb");
								// 	},500)
								// 	that.$refs.jsError.showError('', '验证失败！', 'error');
								// }
								
							} else {
								setTimeout(()=>{
									that.makeSound("sb");
								},500)
								that.$refs.jsError.showError('', res.error, 'error');
							}
						}else{
							setTimeout(()=>{
								that.makeSound("sb");
							},500)
							that.$refs.jsError.showError('', res.message, 'error');
						}
					})
				} else {
					setTimeout(()=>{
						that.makeSound("sb");
					},500)
					this.$refs.jsError.showError('', '请扫描正确的条码！', 'error');
				}
				setTimeout(() => {
					this.barCode = '';
				}, 500);
			
			},
			handleFocus() {
				var _that = this;
				_that.focus = false;
				setTimeout(() => {
					_that.focus = true;
				}, 500)
			},
			iqtyChange(e) {
				this.model.iqty2 = util.toNumberFixed(Number(e))
				console.log(this.model,'model')
				if (this.model.bfixExch == '1') {
					// this.model.inum2 = (e / this.model.ichangeRate).toFixed(config.scaleNum)
					this.model.inum2 = util.toNumberFixed(e / this.model.ichangeRate)
				}
				if (this.model.bfixExch == '2') {
					if(this.model.inum2){
						// this.model.ichangeRate = ( this.model.iqty2 / this.model.inum2).toFixed(config.scaleChangeRate)
						this.model.ichangeRate = util.toNumberFixed( this.model.iqty2 / this.model.inum2 )
					}else{
						this.model.ichangeRate = 0
					}
				}
				this.$forceUpdate()
			},
			inumChange(e) {
				this.model.inum2 = util.toNumberFixed(Number(e))
				if (this.model.bfixExch == '1' || this.model.bfixExch == '2') {
					// this.model.iqty2 = (e * this.model.ichangeRate).toFixed(config.scaleQty)
					this.model.iqty2 =  util.toNumberFixed( e * this.model.ichangeRate )
				}
				
				this.$forceUpdate()
			},
			getOfficeListData() {
				this.$u.api.office.treeData().then(res => {
					this.OfficeList = res
				})
			},
			xzch(){
				uni.navigateTo({
					url: '/pages/mf/llsq/chXz',
					events: {
						// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
						Filter(data) {
							console.log(data)
						}
					},
					success: function(res) {
						// 通过eventChannel向被打开页面传送数据
						//res.eventChannel.emit('initfilter', that.queryData)
					}
				})
			},
			carNoconfirm(v){
				this.model.carNo = v;
				this.$forceUpdate()
			},
			showKeyboard(ref){
				this.$refs[ref].toShow(this.model.carNo)
			},
			cancel() {
				// uni.$emit('refreshData');
				uni.navigateBack({
					delta: 1,
				})
			},
			toFindDetail(model) {
				const that = this
				uni.navigateTo({
					url: '/pages/mf/fh/fhDetailList?hid=' + model.id,
					events: {
						// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
						Filter(data) {

						}
					},
					success: function(res) {
						// 通过eventChannel向被打开页面传送数据
						// res.eventChannel.emit('initfilter', that.filter)
					}
				})
			},
			toAddDetail(model) {
				const that = this
				uni.navigateTo({
					url: '/pages/mf/fh/fhHwAdd?hid=' + model.id,
					events: {
						// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
						Filter(data) {

						}
					},
					success: function(res) {
						// 通过eventChannel向被打开页面传送数据
						// res.eventChannel.emit('initfilter', that.filter)
					}
				})
			},
			delDetail(id) {
				this.querys.id = id;
				uni.showModal({
					title: '删除提示',
					content: '是否删除此详情？',
					confirmColor: '#F54E40',
					success: (res) => {
						if (!res.confirm) {
							this.isdisabled = true
							return false;
						}
						this.$u.api.mf.fjdelDetail(this.querys).then(res => {
							if (res.result=="true") {
								this.$u.toast("删除成功！");
							} else {
								this.$refs.jsError.showError('',res.message,'error');
							}
							this.querys.id = ''
							this.loadList();
						})
					}
				})
			},
			editDetail(item){
				const that=this
				uni.navigateTo({
				  url: '/pages/mf/fjwz/detailForm?model='+JSON.stringify(item),
				  events: {
				    // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
				    Filter(data) {
						
				    }
				  },
				  success: function(res) {
				    // 通过eventChannel向被打开页面传送数据
				    // res.eventChannel.emit('initfilter', that.filter)
				  }
				})
			},
			loadList() {
				this.$u.api.mf.fjfindList(this.query).then(res => {
					if (!res.list || res.list.length == 0) {
						return;
					}
					var data = res.list[0];
					this.model = data;
					this.children = data.mfCarplanFjCList;
				})
			},
			GoaddChild() {
				if (this.model.id == null || this.model.id == '') {
					this.$refs.jsError.showError('','请先保存废旧物资信息！','error');
					return;
				} else {
					const that = this;
					uni.navigateTo({
						url: '/pages/mf/fjwz/detailForm?model=' + JSON.stringify({id:this.model.id}),
						events: {
							// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
							Filter(data) {
								console.log(data)
							}
						},
						success: function(res) {
							// 通过eventChannel向被打开页面传送数据
							//res.eventChannel.emit('initfilter', that.queryData)
						}
					})
				}
			},
			timeConfirm(e) {
				this.model.planDate = e.year + '-' + e.month + '-' + e.day + ' ' + e.hour + ":" + e.minute + ":" + e
					.second;
			},
			submit(data, callback) {
				if(this.icon === 'num') {
					if(this.model.iqty2 == null || this.model.iqty2 == ''){
						this.$refs.jsError.showError('','请修改数量！','error');
						return;
					}
					if(this.model.iqty2 > this.model.syOutQty){
						this.$refs.jsError.showError('','修改的数量不能大于剩余数量'+ this.model.syOutQty,'error');
						return;
					}else{
						let data = {
							id:this.model.id,
							iqty:this.model.iqty2,
							bfixExch:this.model.bfixExch
						};		
						this.model.ichangeRate ? data.ichangeRate = this.model.ichangeRate : ''
						this.model.inum ? data.inum = this.model.inum : ''
						this.$u.api.mf.updateQty(data).then(res => {
							if(res.result == 'true'){
								this.$u.toast(res.message);
								uni.navigateBack({
									delta: 1
								})
							}else{
								this.$refs.jsError.showError('',res.message,'error');
							}
						});
					}
				}
				if(this.icon === 'code'){
					if(this.model.invCode2 == null || this.model.invCode2 == ''){
						this.$refs.jsError.showError('','请先选择存货！','error');
						return;
					}else{
						let data = {
							id:this.model.id,
							invCode:this.model.invCode2,
						};
						this.$u.api.mf.updateInv(data).then(res => {
							if(res.result == 'true'){
								this.$u.toast(res.message);
								uni.navigateBack({
									delta: 1
								})
							}else{
								this.$refs.jsError.showError('',res.message,'error');
							}
						});
					}
				}
				if(this.icon === 'deptname'){
					if(this.model.extDefine31 == null || this.model.extDefine31 == ''){
						this.$refs.jsError.showError('','请先选择部门！','error');
						return;
					}else{
						let data = {
							id : this.model.id,
							extDefine3:this.model.extDefine31
						};
						this.$u.api.mf.whMatAppUpdateBodyInfo(data).then(res => {
							if(res.result == 'true'){
								this.$u.toast(res.message);
								setTimeout(()=>{
									uni.navigateBack({
										delta: 1
									})
								},100)
							}else{
								this.$refs.jsError.showError('',res.message,'error');
							}
						});
					}
				}
			},
		}
	}
</script>
<style lang="less">
	/* .footer {
	position: fixed;
	bottom: 0;
	right:0;
	width: 100%;
	line-height: var(--footer-height);
	background: #ffffff;
	color: #ffffff;
} */
	.text-xxl{
		font-size: 60rpx !important;
	}
	.btn-plus {
		position: fixed;
		bottom: 260rpx;
		right: 40rpx;
		z-index: 2;
		opacity: 0.6;
	}

	.btn-plus:hover {
		opacity: 1;
	}

	.add {
		position: absolute;
		right: 130rpx;
		top: 0;
		margin-right: 0;
	}

	.upload {
		position: absolute;
		right: 65rpx;
		top: 0;
		margin-right: 0;
	}

	.rights {
		position: absolute;
		/* display: inline-block; */
		right: 0;
		top: 0;
		margin-right: 0;
		/* width: 100%; */

	}

	.cu-bar1 {
		min-height: 80px;
	}

	.cu-btn {
		font-size: 16px;
		height: 40px;
	}

	.foot {
		background: #fff;
	}

	.cu-item {
		flex-wrap: wrap;
		padding: 8px 15px !important;
	}

	.title {
		width: 230rpx;
	}

	.cu-modal-slot {
		margin: 42rpx 32rpx 20rpx 32rpx;
		height: 100vh;
		position: relative;
	}

	.cu-modal-header {
		font-size: 38rpx;
		color: #3d3d3d;
		line-height: 40rpx;
		text-align: left;
		font-weight: 500;
	}

	.button {
		font-size: 32rpx;
		color: #666666;
		line-height: 40rpx;
		padding: 12rpx 40rpx;
		margin-bottom: 20rpx;
		background: #e2e2e2;
		border-radius: 180rpx;
	}

	.button:hover {
		background: #3e97b0;
		color: #ffffff;
	}

	.cu-modal-search-title {
		margin: 32rpx 0rpx 20rpx 0rpx;
		text-align: left;
		font-size: 32rpx;
		color: #999999;
		line-height: 40rpx;
	}

	.cu-dialog {
		background: #ffffff;
	}

	.cu-modal-footer {
		padding: 32rpx 32rpx !important;
		width: 100%;

		.cu-btn {
			width: 50%;
		}
	}

	.bg-confirm {
		background: #3e97b0;
		color: #ffffff;
	}
</style>